<template>
  <a-layout :style="{ overflow: 'auto', height: '100%' }">
    <div class="loadding" v-if="loading">
      <img :src="require('@/assets/convert.gif')" alt="" />
    </div>

    <a-layout-header
      :style="{
        height: '50px',
        width: '100vw',
        'line-height': '50px',
        background: 'rgb(51,54,57)',
        color: '#fff',
      }"
    >
      <a-row align="middle" justify="center">
        <a-col span="8">
          {{ filename }}
        </a-col>
        <a-col
          span="8"
          :style="{
            'text-align': 'center',
            display: 'flex',
            'align-items': 'center',
            'justify-content': 'center',
          }"
        >
          <div>
            <input
              type="text"
              style="width: 30px"
              v-model="page"
              @input="pageInput"
              @blur="pageBlur"
              onkeypress="if(window.event.keyCode==13) this.blur()"
              class="input"
            />
            / {{ numPages }}
          </div>
          <div class="divider"></div>
          <div class="button" @click="scaleMinus">
            <a-icon type="minus" />
          </div>
          <span
            ><input
              type="text"
              style="width: 45px"
              v-model="scaleStr"
              @input="scaleInput"
              @blur="scaleBlur"
              onkeypress="if(window.event.keyCode==13) this.blur()"
              class="input"
            />
          </span>
          <div class="button" @click="scalePlus">
            <a-icon type="plus" />
          </div>
          <!-- <div class="divider"></div> -->
        </a-col>
        <a-col
          span="8"
          :style="{
            display: 'flex',
            'align-items': 'center',
            'justify-content': 'flex-end',
            height: '50px',
          }"
        >
          <div class="button" @click="download">
            <a-icon type="download" />
          </div>
          <!-- <div class="button">
            <a-icon type="printer" />
          </div> -->
          <div v-if="collapsed" class="button" @click="collapsed = false">
            <a-icon type="menu-fold" />
          </div>
          <div v-else class="button" @click="collapsed = true">
            <a-icon type="menu-unfold" />
          </div>
        </a-col>
      </a-row>
    </a-layout-header>
    <a-layout :style="{ overflow: 'auto', height: '100%' }">
      <a-layout-content
        @scroll="scroll"
        style="
          display: flex;
          flex-direction: column;
          align-items: center;
          overflow-x: auto;
        "
        ref="pages"
      >
        <Page
          v-for="(page, i) in pages"
          :key="i"
          :page="page"
          :scale="scale"
          :ref="'page' + (i + 1)"
          @sumbit="sumbit"
        />

      </a-layout-content>
 
      <a-layout-sider
        :trigger="null"
        :style="{
          position: 'private',
          overflow: 'auto',
          height: '100%',
          'border-left': collapsed ? 'none' : '2px solid rgba(100,120,107,0.7)',
        }"
        v-model="collapsed"
        :collapsible="true"
        :collapsedWidth="0"
        theme="light"
        width="300"
      >
        <div style="padding: 10px" v-if="!labelEdit" class="list">
          <template v-if="labels.length != 0">
            <Label
              v-for="(label, index) in labels"
              :label="label"
              :index="index"
              :key="label.id"
              @labelClick="labelClick"
              @deleteLabel="deleteLabel"
              @editLabel="() => editLabel(index)"
            />
          </template>
          <div
            v-else
            style="
              position: absolute;
              top: 40%;
              left: 50%;
              transform: translate(-50%, -50%);
            "
          >
            <a-empty />
          </div>
        </div>
        <div style="padding: 10px" v-else>
          <h2>编辑</h2>
          <div style="color: #999; margin: 3px 2px">时间：</div>
          <a-date-picker format="YYYY-MM-DD" v-model="dates" />
          <div style="color: #999; margin: 3px 2px">证据对象：</div>
          <a-textarea v-model="prove" :rows="3" />

          <div style="color: #999; margin: 3px 2px">证据摘录：</div>
          <a-textarea v-model="content" :rows="5" />

          <div style="color: #999; margin: 3px 2px">备注：</div>
          <a-textarea v-model="remark" :rows="3" />

          <div style="margin: 10px 0px; line-height: 30px">
            <template v-for="keyword in keywords">
              <a-tag
                :key="keyword"
                closable
                @close="() => handleClose(keyword)"
              >
                {{ keyword }}
              </a-tag>
            </template>
            <template v-if="keywords.length <= 15">
              <a-input
                v-if="inputVisible"
                ref="input"
                type="text"
                size="small"
                :style="{ width: '78px' }"
                :value="inputValue"
                @change="handleInputChange"
                @blur="handleInputConfirm"
                @keyup.enter="handleInputConfirm"
              />
              <a-tag
                v-else
                style="background: #fff; borderstyle: dashed"
                @click="showInput"
              >
                <a-icon type="plus" /> 添加关键词
              </a-tag>
            </template>
            <div style="margin-top: 30px; text-align: center">
              <a-space size="small">
                <a-button shape="round" @click="cancalSaveLabel">取消</a-button>
                <a-button type="primary" shape="round" @click="saveLabel"
                  >保存</a-button
                >
              </a-space>
            </div>
          </div>
        </div>
      </a-layout-sider>
    </a-layout>
  </a-layout>
</template>

<script>
import Page from "@/components/Page";
import Label from "@/components/Label";
import moment from "moment";

import {
  getPdf,
  getLabels,
  recognition,
  saveCaseEvidence,
  deleteLabel,
} from "@/request/api";

const pdfjsLib = require("pdfjs-dist");

const scaleStep = 10;

export default {
  components: {
    Page,
    Label,
  },
  data() {
    return {
      loading: true, //loading页面是否显示
      collapsed: false, // 侧边栏折叠状态
      filename: "文件名", // 文件名
      numPages: 1, // 页数
      page: 1, //当前页
      scaleStr: "100%",
      scale: 1,
      pages: [],
      labels: [],
      labelEdit: false,

      id: -1,
      p: -1,
      prove: "",
      content: "",
      keywords: [],
      remark: "",
      location: null,
      dates: moment(),
      inputVisible: false,
      inputValue: "",
      caseId:-1
    };
  },
  mounted() {
    this.did = this.$route.params.did;
    this.caseId= this.$route.params.id;
    if (this.did) {
      this.getPdf(this.did);
      this.getLabels(this.did);
    } else {
      console.error("文档id不存在");
      this.$message.error("文档id不存在");
      this.$router.replace("/404");
    }
  },
  methods: {
    moment,
    pageInput() {
      if (this.page == "") {
        return false;
      }
      this.page = this.page.replace(/[^\d]/g, "");
      if (this.page > this.numPages) {
        this.page = this.numPages;
      } else if (this.page < 1) {
        this.page = 1;
      }
    },
    pageBlur() {
      if (this.page == "") {
        this.page = 1;
      }
      // 跳转到对应的page
      this.gotoPage(this.page);
    },
    scaleInput() {
      if (this.page == "") {
        return false;
      }
      this.scaleStr = this.scaleStr.replace(/[^\d%]/g, "");
      let index = this.scaleStr.indexOf("%");
      if (index != this.scaleStr.length - 1) {
        this.scaleStr = this.scaleStr.replace(/[^\d]/g, "");
      }
    },
    scaleBlur() {
      if (this.scaleStr == "") {
        this.scaleStr = "100%";
      }
      let s;
      if (this.scaleStr.indexOf("%") < 0) {
        s = Number(this.scaleStr);
      } else {
        s = Number(this.scaleStr.substr(0, this.scaleStr.length - 1));
      }
      if (s > 300) {
        s = 300;
        this.scaleStr = "300%";
      }
      if (s < 30) {
        s = 30;
        this.scaleStr = "30%";
      }
      if (this.scaleStr.indexOf("%") < 0) {
        this.scaleStr = this.scaleStr + "%";
      }
      this.scale = s / 100;
      console.log(this.scaleStr);
    },
    gotoPage(page) {
      let pageOffsetTop = this.$refs["page" + page][0].$el.offsetTop - 60;
      this.$refs.pages.$el.scrollTop = pageOffsetTop;
    },
    scaleMinus() {
      let s = Number(this.scaleStr.substr(0, this.scaleStr.length - 1));
      s = s - scaleStep;
      if (s < 30) {
        s = 30;
      }
      this.scaleStr = s + "%";
      this.scale = s / 100;
    },
    scalePlus() {
      let s = Number(this.scaleStr.substr(0, this.scaleStr.length - 1));
      s = s + scaleStep;
      if (s > 300) {
        s = 300;
      }
      this.scaleStr = s + "%";
      this.scale = s / 100;
    },
    // 调用接口,获取pdf
    getPdf(did) {
      getPdf(did)
        .then((data) => {
          let filename = data.fileName;
          let pdf = data.path;
          this.filename = filename;
          this.loadPdf(pdf);
        })
        .catch((err) => {
          console.log(err)
          this.$message.error("文档不存在");
          this.$router.replace("/404");
        });
    },
    loadPdf(pdfUrl) {
      pdfjsLib.GlobalWorkerOptions.workerSrc = "pdf.worker.min.js";
      const res = pdfjsLib.getDocument(pdfUrl);
      res.promise.then((pdf) => {
        this.numPages = pdf.numPages;
        let pages = [];
        for (let i = 1; i <= pdf.numPages; i++) {
          pages.push(pdf.getPage(i));
        }
        this.pages = [...pages];
      });
      setTimeout(() => {
        this.loading = false;
      }, 1000);
    },
    scroll() {
      if (this.pages.length > 0) {
        let scrollTop = this.$refs.pages.$el.scrollTop;
        for (let index = 1; index <= this.pages.length; index++) {
          let pageOffsetTop = this.$refs["page" + index][0].$el.offsetTop - 10;
          let pageClientHeight = this.$refs["page" + index][0].$el.clientHeight;
          if (scrollTop < pageOffsetTop + (pageClientHeight / 4) * 3) {
            this.page = index;

            return;
          }
        }
      }
    },
    // 调用接口
    getLabels(did) {
      getLabels(did)
        .then((data) => {
          this.labels = data;
          this.drawAllLables();
        })
        .catch(() => {});
    },
    drawAllLables() {
      // 清除所有的标记
      for (let i = 1; i <= this.numPages; i++) {
        this.$refs["page" + i] && this.$refs["page" + i][0].clearLabelsCanvas();
      }
      this.labels.forEach((label) => {
        this.drawLable(label.page, label.location);
      });
    },
    drawLable(page, location) {
      if (this.$refs["page" + page]) {
        this.$refs["page" + page][0].drawAndSaveLabel(location);
      } else {
        setTimeout(() => {
          this.drawLable(page, location);
        }, 500);
      }
    },
    labelClick(page) {
      this.gotoPage(page);
    },
    // 识别文字
    sumbit(page, location, imgBase64) {
      let keywords = [];
      let labelEdit = true; // 打开 “编辑” 页面
      let collapsed = false;
      let prove = "";
      let remark = "";
      let p = page;
      recognition({ image: imgBase64 })
        .then((data) => {
          let content = data;
          Object.assign(this, {
            id: -1,
            labelEdit,
            collapsed,
            p,
            location,
            prove,
            content,
            keywords,
            remark,
          });
        })
        .catch(() => {});
    },
    addLabel(id, page, location, content, dates, keywords) {
      this.labels = [
        {
          id,
          page: page,
          location,
          content,
          dates,
          keywords,
        },
        ...this.labels,
      ];
      this.drawLable(page, location);
    },
    showInput() {
      this.inputVisible = true;
      this.$nextTick(function () {
        this.$refs.input.focus();
      });
    },

    handleClose(removedKeyword) {
      const keywords = this.keywords.filter(
        (keyword) => keyword !== removedKeyword
      );
      this.keywords = keywords;
    },
    handleInputChange(e) {
      this.inputValue = e.target.value;
    },
    handleInputConfirm() {
      const inputValue = this.inputValue;
      let keywords = this.keywords;

      if (inputValue === undefined || inputValue === "") {
        this.inputVisible = false;
        return;
      }
      if (keywords.indexOf(inputValue) !== -1) {
        this.$message.error("关键字重复");
        return;
      }
      keywords = [...keywords, inputValue];
      Object.assign(this, {
        inputVisible: false,
        inputValue: "",
        keywords,
      });
    },
    cancalSaveLabel() {
      Object.assign(this, {
        inputVisible: false,
        inputValue: "",
        keywords: [],
        dates: null,
        content: "",
        labelEdit: false,
        prove: "",
        remark: "",
        p: -1,
        location: "",
        id: -1
      });
    },
    // 调用网络接口
    saveLabel() {
      let dates  ;
  
      if (this.dates == null) {
        dates = "";
      } else {
        dates = this.dates.format("YYYY-MM-DD");
      }

      if (this.p < 0 && this.id > 0) {
        saveCaseEvidence(this.caseId,this.id, {
          did: this.did,
          content: this.content,
          keywords: this.keywords,
          location: this.location,
          remark: this.remark,
          prove: this.prove,
          dates: dates
        })
          .then(() => {
            this.getLabels(this.did);
            this.cancalSaveLabel();
            this.$message.success("保存成功");
          })
          .catch(() => {});
      } else {
        saveCaseEvidence(this.caseId,null, {
          did: this.did,
          page: this.p,
          content: this.content,
          keywords: this.keywords,
          location: this.location,
          remark: this.remark,
          prove: this.prove,
          dates: dates,
          zjmc:this.filename
        })
          .then(() => {
            this.getLabels(this.did);
            this.cancalSaveLabel();
            this.$message.success("保存成功");
          })
          .catch(() => {});
      }
    },
    deleteLabel(id) {
      deleteLabel(id)
        .then(() => {
          this.$message.success("删除成功");
          this.getLabels(this.did);
        })
        .catch(() => {});
    },
    editLabel(i) {
      let label = this.labels[i];
      Object.assign(this, {
        p: -1,
        id: label.id,
        labelEdit: true,
        location: label.location,
        prove: label.prove,
        content: label.content,
        keywords: label.keywords,
        remark: label.remark,
        dates: moment(label.dates, "YYYY-MM-DD"),
      });
    },
    download(){
      window.open('/weaver/weaver.file.FileDownload?download=1&fileid='+this.did)
    }
  },
  computed: {},
  watch: {},
};
</script>

<style lang="stylus" scoped>
.button {
  font-size: 16px;
  padding: 5px;
  margin: 0px 3px;
  cursor: pointer;
  border-radius: 50%;
  width: 28px;
  height: 28px;
  position: relative;

  &>* {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }

  &:hover {
    background: #666;
  }
}

.divider {
  height: 15px;
  width: 1px;
  background: #888;
  margin: 0px 10px;
}

.input {
  font-size: 12px;
  height: 20px;
  text-align: center;
  background: #000;
  color: #fff;
  border: none;
  outline: none;
}

.loadding {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: #fff;
  z-index: 999;

  img {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }
}
</style>